/**
 * 用户认证相关API服务
 * 包括用户注册、登录、刷新令牌等功能
 */
import api from './api';

const AuthService = {
  /**
   * 用户注册
   * @param {Object} userData - 用户注册数据
   * @param {string} userData.username - 用户名
   * @param {string} userData.email - 邮箱
   * @param {string} userData.password - 密码
   * @return {Promise} 注册结果Promise
   */
  register: async (userData) => {
    return await api.post('/api/auth/register', userData);
  },

  /**
   * 用户登录
   * @param {Object} credentials - 登录凭证
   * @param {string} credentials.username - 用户名
   * @param {string} credentials.password - 密码
   * @return {Promise} 登录结果Promise
   */
  login: async (credentials) => {
    const response = await api.post('/api/auth/login', credentials);
    if (response.data && response.data.token) {
      // 存储token到localStorage
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('refreshToken', response.data.refreshToken);
      localStorage.setItem('expiresIn', response.data.expiresIn);
      localStorage.setItem('tokenExpiry', new Date().getTime() + response.data.expiresIn * 1000);
      
      // 存储用户信息
      if (response.data.user) {
        localStorage.setItem('userData', JSON.stringify(response.data.user));
      } else {
        // 如果后端没有直接返回用户信息，创建一个基本用户对象并保存
        const basicUser = {
          username: credentials.username,
          id: response.data.userId || 0,
          email: response.data.email || '',
          role: response.data.role || 'user',
          isPro: response.data.isPro || false
        };
        localStorage.setItem('userData', JSON.stringify(basicUser));
      }
    }
    return response;
  },

  /**
   * 注销登录
   */
  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('expiresIn');
    localStorage.removeItem('tokenExpiry');
    localStorage.removeItem('userData');
  },

  /**
   * 刷新访问令牌
   * @return {Promise} 刷新结果Promise
   */
  refreshToken: async () => {
    const refreshToken = localStorage.getItem('refreshToken');
    if (!refreshToken) {
      return Promise.reject(new Error('没有刷新令牌'));
    }

    try {
      const response = await api.post('/api/auth/refresh', { refreshToken });
      if (response.data && response.data.token) {
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('refreshToken', response.data.refreshToken);
        localStorage.setItem('expiresIn', response.data.expiresIn);
        localStorage.setItem('tokenExpiry', new Date().getTime() + response.data.expiresIn * 1000);
      }
      return response;
    } catch (error) {
      AuthService.logout();
      return Promise.reject(error);
    }
  },

  /**
   * 检查令牌是否过期
   * @return {boolean} 是否需要刷新令牌
   */
  isTokenExpired: () => {
    const tokenExpiry = localStorage.getItem('tokenExpiry');
    if (!tokenExpiry) return true;
    
    // 如果token有效期小于5分钟，则需要刷新
    return new Date().getTime() > (parseInt(tokenExpiry) - 300000);
  }
};

export default AuthService; 